﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrankShaftAnalysisSystem.Devices
{
    public class DistanceEastenGauge
    {
        private static readonly DistanceEastenGauge instance = new DistanceEastenGauge();

        /// <summary>
        /// 显式的静态构造函数用来告诉C#编译器在其内容实例化之前不要标记其类型
        /// 静态构造函数是C#的一个新特性，其实好像很少用到。 
        /// 不过当我们想初始化一些静态变量的时候就需要用到它了。 这个构造函数是属于类的，
        /// 而不是属于哪里实例的，就是说这个构造函数只会被执行一次。 
        /// 也就是在创建第一个实例或引用任何静态成员之前，由.NET自动调用
        /// </summary>
        static DistanceEastenGauge() { }

        private DistanceEastenGauge()
        {
            Device = new EastenGauge("192.168.3.111", 502);
            var compress = Properties.Settings.Default.PenCompress;
            if (compress > 0) PenTargetCompression = compress;
        }

        public static DistanceEastenGauge Instance
        {
            get
            {
                return instance;
            }
        }

        [Description("MU5设备")]
        public EastenGauge Device;

        [Description("弹簧目标压缩量")]
        public double PenTargetCompression { get; set; } = 1800; // 2000um = 2mm

        public double Pen1InitPos { get; set; }
        public double Pen2InitPos { get; set; }
        public void LoadSetting()
        {
            Pen1InitPos = Properties.Settings.Default.Pen1InitPos;
            Pen2InitPos = Properties.Settings.Default.Pen2InitPos;
        }

        /// <summary>
        /// 获得笔的压缩量
        /// </summary>
        /// <param name="num">通道</param>
        /// <returns>单位um</returns>
        public double GetPenCompression(int num)
        {
            if (num > 1)
                throw new Exception("Channel Not Supported.");
            double[] pen_init = new double[2] { Pen1InitPos, Pen2InitPos };
            double[] pen_now = new double[2] { Device.ChannelData[0], Device.ChannelData[1] };
            return pen_init[num] - pen_now[num];
        }

        public bool PenCompressionReached()
        {
            var p1 = GetPenCompression(0);
            var p2 = GetPenCompression(1);
            return (p1 >= PenTargetCompression * 0.9 || p2 >= PenTargetCompression * 0.9);
        }
    }
}
